package com.xpz.reggie.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xpz.reggie.common.R;
import com.xpz.reggie.dto.OrdersDto;
import com.xpz.reggie.entity.OrderDetail;
import com.xpz.reggie.entity.Orders;
import com.xpz.reggie.service.OrderDetailService;
import com.xpz.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 * 订单提交
 * @author wxc
 * @date 2023/2/26 23:24
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class Orderontroller {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;



    /**
     * 用户订单提交
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 订单已送达
     * @param orders
     * @return
     */
    @PostMapping
    public R<String> send(@RequestBody Orders orders){
        Long ordersId = orders.getId();
        Integer status = orders.getStatus();

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId,ordersId);

        Orders one = orderService.getOne(queryWrapper);
        one.setStatus(status);
        orderService.updateById(one);

        return R.success("派送成功");
    }

    /**
     * 订单管理
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page,int pageSize){
        //分页构造器
        Page<Orders> pageInfo = new Page<>();
        Page<OrdersDto> orderDetailPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);

        orderService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,orderDetailPage,"recorde");
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list = records.stream().map((item) ->{
           OrdersDto ordersDto = new OrdersDto();
           BeanUtils.copyProperties(item,ordersDto);
           String name ="用户" + item.getUserId();
           ordersDto.setUserName(name);
           return ordersDto;
        }).collect(Collectors.toList());
        orderDetailPage.setRecords(list);


        return R.success(orderDetailPage);
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
//    @Transactional
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){

        //取得orders
        Long id = orders.getId();
        Orders ordersById = orderService.getById(id);
        //设置订单号
        long orderId = IdWorker.getId();
        ordersById.setId(orderId);

        String number = String.valueOf(orderId);
        ordersById.setNumber(number);

        //下单时间
        ordersById.setOrderTime(LocalDateTime.now());
        ordersById.setCheckoutTime(LocalDateTime.now());
        ordersById.setStatus(2);

        //向订单表插入数据
        orderService.save(ordersById);

        //修改订单表
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> list = orderDetailService.list(queryWrapper);
        list.stream().map((item) ->{
            long detailId = IdWorker.getId();
            //设置订单号码
            item.setOrderId(orderId);
            item.setId(detailId);
            return item;

        }).collect(Collectors.toList());

        //向订单中插入多条数据
        orderDetailService.saveBatch(list);
        return R.success("再来一单");
    }

    /**
     * 后端订单管理
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> Page(int page,int pageSize,String number,String beginTime,String endTime){

        //构造分页构造器
        Page<Orders> pageInfo = new Page<Orders>(page,pageSize);

        Page<OrdersDto> ordersDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //模糊查询
        queryWrapper.like(!StringUtils.isEmpty(number),Orders::getNumber,number);
        //根据Datetime进行时间范围查询
        log.info("开始时间：{}",beginTime);
        log.info("结束时间：{}",endTime);

        if(beginTime!=null&&endTime!=null){
            queryWrapper.ge(Orders::getOrderTime,beginTime);
            queryWrapper.le(Orders::getOrderTime,endTime);
        }
        //添加条件排序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //进行分页查询
        orderService.page(pageInfo,queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,ordersDtoPage,"records");
        List<Orders> records = pageInfo.getRecords();

        List<OrdersDto> list =records.stream().map((item)->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            String name = "用户"+item.getUserId();
            ordersDto.setUserName(name);
            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(list);
        return R.success(ordersDtoPage);
    }

    /**
     * 后台订单派送信息修改
     * @param map
     * @return
     */
    @PutMapping
    public R orderStatusChange(@RequestBody Map map){
        Object id = map.get("id");
        Long orderId = Long.parseLong(String.valueOf(id));
        Integer status = Integer.parseInt(String.valueOf(map.get("status")));

        if (orderId ==null ||status==null){
            return R.error("信息错误");
        }

        Orders orders =orderService.getById(orderId);
        orders.setStatus(status);
        orderService.updateById(orders);

        return R.success("修改成功");
    }


}
